import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
  Text,
  ScrollView,
  router,
  publishDps,
  exitMiniProgram,
  navigateTo,
  hideMenuButton,
  Button,
  getElementById,
} from '@ray-js/ray';
import clsx from 'clsx';
import {
  useDevice,
  useActions,
  useProps,
  useStructuredActions,
  useStructuredProps,
} from '@ray-js/panel-sdk';
import { useThrottleFn, useDebounceFn } from 'ahooks';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import Strings from '@/i18n';
import { Slider, Switch, ConfigProvider, Picker, ActionSheet, NavBar } from '@ray-js/smart-ui';
import CountdownActionSheet from '@ray-js/countdown-action-sheet';
import _, { differenceWith, throttle } from 'lodash';
import { Cell, Image, View } from '@/components';
import { LampColorSlider } from '@ray-js/components-ty-lamp';
import { decodeScene, formatCurrentTime, formatSecondsToHMS } from '@/utils';
import ColorPic from '@/components/ColorPic';
import { rgb2hsv, hsv2rgbString } from '@ray-js/panel-sdk/lib/utils/color';

import styles from './index.module.less';
import res from '../../../public/newImage';

export const VoiceList = {
  nature: new Array(10).fill(1).map((_, index) => {
    return {
      code: `ringtone_${index + 1}`,
      name: Strings.getLang(`nature_${index + 1}`),
      pic: res[`nature_${index + 1}`],
      picActive: res[`nature_${index + 1}_active`],
      type: 'nature',
    };
  }),
  environment: new Array(9).fill(1).map((_, index) => {
    return {
      code: `ringtone_${index + 1}`,
      name: Strings.getLang(`environment_${index + 1}`),
      pic: res[`environment_${index + 1}`],
      picActive: res[`environment_${index + 1}_active`],
      type: 'environment',
    };
  }),
  thing: new Array(11).fill(1).map((_, index) => {
    return {
      code: `ringtone_${index + 1}`,
      name: Strings.getLang(`thing_${index + 1}`),
      pic: res[`thing_${index + 1}`],
      picActive: res[`thing_${index + 1}_active`],
      type: 'thing',
    };
  }),
  sleep: new Array(13).fill(1).map((_, index) => {
    return {
      code: `ringtone_${index + 1}`,
      name: Strings.getLang(`sleep_${index + 1}`),
      pic: res[`sleep_${index + 1}`],
      picActive: res[`sleep_${index + 1}_active`],
      type: 'sleep',
    };
  }),
};

const HeaderHeight = 59;

const sysInfo = getCachedSystemInfo();

const sceneCodeList = new Array(8).fill(1).map((_, index) => `customize_scene_${index + 1}`);

export function Home() {
  const deviceName = useDevice(d => d?.devInfo?.name);
  const deviceId = useDevice(d => d.devInfo.devId);
  const groupId = useDevice(d => d.devInfo.groupId);

  const scrollRef = useRef(null);
  console.log('🐫 ~ file: index.tsx:83 ~ scrollRef:', scrollRef);
  const [scrollEnabled, setScrollEnabled] = useState(true);

  const dpActions = useActions();
  const dpStructuredActions = useStructuredActions();
  const colour = useStructuredProps(props => props.colour_data);
  const lightMode = useProps(props => props.light_mode);

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const volumeSet = useProps(props => +props.volume_set);

  const brightValue = useProps(props => +props.bright_value);

  const getLightSliderValue = () => {
    if (lightMode === 'breathe_lamp') return 1000;
    if (lightMode === 'color_ligth') return colour.value;
    if (lightMode === 'lighting_lamp') return brightValue;
  };

  const getLightSliderMinValue = () => {
    if (lightMode === 'lighting_lamp') return 10;
    return 0;
  };

  const getLightSliderDisable = () => {
    if (!switchLed) return true;
    if (lightMode === 'breathe_lamp') return true;
    return false;
  };

  const [brightValueStr, setBrightValueStr] = useState(getLightSliderValue());

  const [volumeSetStr, setVolumeSetStr] = useState(volumeSet);

  useEffect(() => {
    setBrightValueStr(getLightSliderValue());
  }, [brightValue, colour, lightMode]);

  useEffect(() => {
    setVolumeSetStr(volumeSet);
  }, [volumeSet]);

  const timeMode = useProps(props => props.time_mode);

  const unit = useRef(timeMode);

  const [actions, setActions] = React.useState([
    { id: 0, name: '12h', checked: timeMode === '12h' },
    { id: 1, name: '24h', checked: timeMode === '24h' },
  ]);

  useEffect(() => {
    setActions([
      { id: 0, name: '12h', checked: timeMode === '12h' },
      { id: 1, name: '24h', checked: timeMode === '24h' },
    ]);
  }, [timeMode]);

  const setTimeMode = evt => {
    const { id } = evt.detail;
    const newActions = actions.map(item => {
      if (item.id === id) return { ...item, checked: true };
      return { ...item, checked: false };
    });
    setActions(newActions);
    publishDps({
      time_mode: newActions.find(item => item.checked).name,
    });
  };


  const lock = useProps(props => props.lock);
  const setLock = (val: boolean) => {
    // dpActions.lock.toggel()
    publishDps({
      lock: val,
    });
  };
  const countDown = useProps(props => props.count_down ?? 0);

  const [totalSecond, setTotalSecond] = useState(+countDown * 60 || 0);

  useEffect(() => {
    setTotalSecond(+countDown * 60 || 0);
  }, [countDown]);


  useEffect(() => {
    let timer;
    if (totalSecond > 0) {
      timer = setInterval(() => {
        setTotalSecond(totalSecond - 1);
      }, 1000);
    } else {
      clearInterval(timer);
      setTotalSecond(0);
    }
    return () => {
      clearInterval(timer);
    };
  }, [totalSecond]);

  const { hourText, minuteText, secondText } = formatSecondsToHMS(totalSecond);


  const countDownText = totalSecond ? `${hourText}:${minuteText}:${secondText}` : '';

  const setCountDown = (val: number) => {
    publishDps({
      count_down: val,
    });
  };

  const setMusicSet = (val: string) => {
    publishDps({
      music_set: val,
      ringtone: 'ringtone_1',
    });
  };

  const switchMusic = useProps(props => props.switch_music);

  const musicSet = useProps(props => props.music_set);
  const ringtone = useProps(props => props.ringtone);

  const switchLed = useProps(props => props.switch_led);

  const setLightMode = (val: string) => {
    publishDps({
      light_mode: val,
    });
  };

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const [showCountDown, setShowCountDown] = React.useState(false);

  const [showUnit, setShowUnit] = React.useState(false);

  const showTransformBox = useProps(props => props.switch_led);

  const setShowTransformBox = (val: boolean) => {
    // setShowTransformBox(val);
    publishDps({
      switch_led: !showTransformBox,
    });
  };

  const [showTransformVoiceBox, setShowTransformVoiceBox] = useState(true);

  const setVolumeSet = (value: number) => {
    dpActions.volume_set.set(value, { throttle: 300 });
  };

  const setBrightValue = (value: number) => {
    if (lightMode === 'lighting_lamp') {
      dpActions.bright_value.set(value, { throttle: 300 });
    }

    if (lightMode === 'color_ligth') {
      dpStructuredActions.colour_data.set({
        ...colour,
        value,
      });
    }
  };

  const onClickLeft = () => {
    exitMiniProgram();
  };

  const CurrentMusic = VoiceList[musicSet].find(item => item.code === ringtone) || {};
  const wbSwitch = useProps(props => props.wb_switch);

  const curScene = useProps(props => props.customize_scene);

  const scene1 = useProps(props => props.customize_scene_1);
  const scene2 = useProps(props => props.customize_scene_2);
  const scene3 = useProps(props => props.customize_scene_3);
  const scene4 = useProps(props => props.customize_scene_4);
  const scene5 = useProps(props => props.customize_scene_5);
  const scene6 = useProps(props => props.customize_scene_6);
  const scene7 = useProps(props => props.customize_scene_7);
  const scene8 = useProps(props => props.customize_scene_8);
  const curTime = useProps(props => ((props.cur_time || 0) as unknown) as number);

  const [{ hours, minutes, period }, setCurrentTime] = useState(
    formatCurrentTime(curTime || 0, timeMode)
  );

  useEffect(() => {
    setCurrentTime(formatCurrentTime(curTime || 0, timeMode));
  }, [curTime, timeMode]);

  const sceneList = [scene1, scene2, scene3, scene4, scene5, scene6, scene7, scene8]
    .map((item, index) => {
      return {
        code: `customize_scene_${index + 1}`,
        ...decodeScene(item),
        type: `mode_${index + 1}`,
      };
    })
    .filter(item => item.setted !== false);

  const settledSceneCode = sceneList.map(item => item.code);

  const addScene = () => {
    const newCode = differenceWith(sceneCodeList, settledSceneCode)[0];
    router.push(`/sceneEdit?code=${newCode}`);
  };

  const getColor = () => {
    if (!switchLed) {
      return 'rgba(0,0,0,0)';
    }

    if (lightMode === 'lighting_lamp') {
      return '#F4EBBE';
    }

    if (lightMode === 'color_ligth') {
      const color = hsv2rgbString(colour.hue, colour.saturation / 10, colour.value / 10);

      return color;
    }

    if (lightMode === 'breathe_lamp') {
      return '#F4EBBE';
    }
  };

  return (
    <View className={styles.view}>
      <NavBar
        title={deviceName}
        className={styles.navBar}
        customClass={styles.borBot}
        slot={{
          right: (
            <View className={styles.tabTopIconWrap}>
              {['setting'].map(item => (
                <Image
                  onClick={() => {
                    const jumpUrl = `functional://settings/detail?deviceId=${deviceId ||
                      ''}&groupId=${groupId || ''}`;
                    navigateTo({
                      url: jumpUrl,
                    });
                  }}
                  src={`/images/${item}.png`}
                  key={item}
                />
              ))}
            </View>
          ),
          left: (
            <View className={styles.tabTopIconWrapLeft} onClick={onClickLeft}>
              {['back'].map(item => (
                <Image src={`/newImage/${item}.png`} key={item} />
              ))}
            </View>
          ),
        }}
      />
      <ScrollView
        scrollY={scrollEnabled}
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(100vh - ${HeaderHeight}px  - ${sysInfo.statusBarHeight}px)`,
        }}
        // id={'scroll'}
        // scrollTop={scrollTop}
        // onScroll={event => onScroll(event, 'Y')}
      >
        <View
          style={{
            marginTop: 10,
          }}
        >
          <View className={styles.headerBtn}>
            <Button
              className={clsx(styles.wkBtm, wbSwitch === 'white_noice' && styles.wkBtmActive)}
              onClick={() => {
                publishDps({
                  wb_switch: 'white_noice',
                });
              }}
            >
              <Text>{Strings.getLang('whiteNoice')}</Text>
            </Button>

            <Button
              className={clsx(styles.wkBtm, wbSwitch === 'off' && styles.wkBtmActive)}
              onClick={() => {
                publishDps({
                  wb_switch: 'off',
                });
              }}
            >
              <Text>{Strings.getLang('mode_off')}</Text>
            </Button>

            <Button
              className={clsx(styles.wkBtm, wbSwitch === 'bluetooth' && styles.wkBtmActive)}
              onClick={() => {
                publishDps({
                  wb_switch: 'bluetooth',
                });
              }}
            >
              <Text>{Strings.getLang('blueToosh')}</Text>
            </Button>
          </View>
          <View className={styles.card}>
            <View className={styles.cardContent}>
              <View className={styles.musicBox}>
                <View className={styles.musicContent}>
                  <View className={styles.currentMusic}>
                    <Image
                      src={switchMusic ? res.currentMusic : res.mute}
                      className={styles.current}
                      style={{
                        width: '72rpx',
                        height: '78rpx',
                      }}
                    />
                    <Text className={styles.currentMusicName}>{CurrentMusic?.name}</Text>
                  </View>

                  <View className={styles.controlBox}>
                    <Image
                      src={res.next}
                      className={styles.control}
                      onClick={() => {
                        publishDps({
                          prev: true,
                        });
                      }}
                    />
                    <Image
                      src={switchMusic ? res.pause : res.play}
                      className={styles.play}
                      onClick={() => {
                        publishDps({
                          switch_music: !switchMusic,
                        });
                      }}
                    />
                    <Image
                      src={res.prev}
                      className={styles.control}
                      onClick={() => {
                        publishDps({
                          next: true,
                        });
                      }}
                    />
                  </View>
                </View>
                <View
                  className={styles.logoBox}
                  onClick={() => {
                    publishDps({
                      switch_led: !switchLed,
                    });
                  }}
                >
                  <View className={styles.logo}>
                    {switchLed ? (
                      <ColorPic
                        className={clsx(
                          styles.logoTop,
                          lightMode === 'breathe_lamp' && styles.breath
                        )}
                        color={getColor()}
                      />
                    ) : (
                      <Image className={styles.logoTop} src={res.lightTop} />
                    )}
                    <Image className={styles.logoBot} src={res.lightBot} />
                  </View>
                  {/* <View className={styles.numberView}>
                    <Text
                      style={{
                        color: '#fff',
                        fontFamily: 'sans-serif',
                        fontSize: timeMode === '12h' ? 24 : 30,
                        fontWeight: 'bold',
                      }}
                    >{`${hours}:${minutes}${period}`}</Text>
                  </View> */}
                </View>
              </View>

              <View className={styles.sliderBox}>
                <Image src={res.voice} className={styles.sliderPic} />
                <Slider
                  maxTrackHeight="18rpx"
                  minTrackHeight="18rpx"
                  thumbHeight="20px"
                  thumbWidth="20px"
                  max={100}
                  min={1}
                  step={1}
                  value={volumeSet}
                  maxTrackColor="#052F46"
                  minTrackColor="#E2E742"
                  thumbColor="#fff"
                  // onChange={value => setVolumeSetStr(value)}
                  onAfterChange={value => {
                    setVolumeSetStr(value);
                    setVolumeSet(value);
                  }}
                  moveEventName="changeVoice"
                  style={{
                    width: `550rpx`,
                  }}
                />
                <View className={styles.sliderText}>{volumeSet}%</View>
              </View>

              <View className={styles.sliderBox}>
                <Image src={res.light} className={styles.sliderPic} />
                <Slider
                  maxTrackHeight="18rpx"
                  minTrackHeight="18rpx"
                  thumbHeight="20px"
                  thumbWidth="20px"
                  maxTrackColor="#052F46"
                  minTrackColor={getLightSliderDisable() ? '#E2E74250' : '#E2E742'}
                  thumbColor="#fff"
                  max={1000}
                  min={getLightSliderMinValue()}
                  step={10}
                  value={getLightSliderValue()}
                  disabled={getLightSliderDisable()}
                  onAfterChange={value => {
                    setBrightValue(value);
                  }}
                  moveEventName="changeBright"
                  style={{
                    width: `550rpx`,
                  }}
                />
                <View className={styles.sliderText}>
                  <Text>{(brightValueStr / 10).toFixed(0)}%</Text>
                </View>
              </View>
            </View>
          </View>

          <Cell
            title={Strings.getLang('clock')}
            isLink
            customClass={styles.cell}
            icon={res.clock}
            onClick={() => {
              // router.push('/clock');
              handleJump('clock');
            }}
          />

          <Cell
            title={Strings.getLang('countDown')}
            isLink
            icon={res.countDown}
            customClass={styles.cell}
            value={countDownText}
            onClick={() => {
              // toggleBottomSheet();
              setShowCountDown(true);
            }}
          />

          <Cell icon={res.lock} title={Strings.getLang('lock')} customClass={styles.cell}>
            <Switch
              checked={lock}
              size="24px"
              onChange={e => {
                setLock(e.detail);
              }}
            />
          </Cell>

          <Cell
            title={Strings.getLang('timeUnit')}
            customClass={styles.cell}
            icon={res.unit}
            onClick={() => {
              setShowUnit(true);
            }}
            value={timeMode}
            isLink
          />

          <View className={styles.customCellBox}>
            <Cell
              title={Strings.getLang('mode')}
              icon={res.scene}
              iconClass={styles.sceneIcon}
              needMargin={false}
              customClass={clsx(styles.cell, styles.transformCell)}
            >
              <Image
                src={res.edit}
                className={styles.editIcon}
                onClick={() => {
                  handleJump('scene');
                }}
              />
            </Cell>
            <View className={clsx(styles.transformBox, styles.transformBoxActive)}>
              <View
                className={styles.voiceContent}
                style={{
                  background: 'transparent',
                  marginTop: -20,
                }}
              >
                {sceneList.map(item => {
                  const CurrentMusic =
                    VoiceList[item.musicSet]?.find(e => e.code === item.music) ||
                    VoiceList.nature[0];

                  const isActive = item.type === curScene;

                  return (
                    <Image
                      src={isActive ? CurrentMusic?.picActive : CurrentMusic?.pic}
                      key={item.code}
                      className={styles.voiceItem}
                      onClick={() => {
                        publishDps({
                          customize_scene: item.type,
                        });
                      }}
                    />
                  );
                })}

                {sceneList.length < 8 ? (
                  <Image
                    src={res.add}
                    key="add"
                    className={styles.voiceItem}
                    onClick={() => {
                      addScene();
                    }}
                  />
                ) : null}
              </View>
            </View>
          </View>

          <View className={styles.customCellBox}>
            <Cell
              title={Strings.getLang('lamp')}
              icon={res.lamp}
              // iconClass={styles.lightIcon}
              needMargin={false}
              customClass={clsx(styles.cellNoBtm, styles.transformCell)}
            >
              <Switch
                checked={showTransformBox}
                size="24px"
                onChange={e => {
                  setShowTransformBox(!showTransformBox);
                }}
              />
            </Cell>
            <View
              className={clsx(styles.transformBox, showTransformBox && styles.transformBoxActive)}
            >
              <View className={styles.wrapper}>
                {['lighting_lamp', 'color_ligth', 'breathe_lamp'].map(item => {
                  return (
                    <View
                      onClick={() => {
                        setLightMode(item);
                      }}
                      key={item}
                      className={clsx(styles.tab, lightMode === item && styles.tabActive)}
                    >
                      <Text>{Strings.getLang(item)}</Text>
                    </View>
                  );
                })}
              </View>
              <View
                style={{
                  marginTop: 20,
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
              >
                {lightMode === 'color_ligth' && (
                  <LampColorSlider
                    value={colour.hue}
                    trackStyle={{
                      height: '10px',
                      width: `640rpx`,
                      borderRadius: '5px',
                      marginTop: 20,
                    }}
                    thumbStyle={{
                      height: '20px',
                      width: '20px',
                      borderRadius: '10px',
                      borderColor: 'transparent',
                    }}
                    onTouchMove={val => {
                      // setHue(val);
                    }}
                    onTouchEnd={val => {
                      // setHue(val);
                      dpStructuredActions.colour_data.set({
                        ...colour,
                        hue: val,
                      });
                    }}
                  />
                )}
              </View>
            </View>
          </View>

          <View className={styles.customCellBox}>
            <Cell
              title={Strings.getLang('voiceType')}
              customClass={styles.transformCell}
              isLink
              arrowDirection={
                showTransformVoiceBox? 'down': 'right'
              }
              icon={res.voiceType}
              onClick={() => {
                setShowTransformVoiceBox(!showTransformVoiceBox);
              }}
            />

            <View
              className={clsx(
                styles.transformBox,
                showTransformVoiceBox && styles.transformBoxActive
              )}
            >
              <View className={styles.wrapper}>
                {['nature', 'environment', 'thing', 'sleep'].map(item => {
                  return (
                    <View
                      onClick={() => {
                        setMusicSet(item);
                      }}
                      key={item}
                      className={clsx(styles.tabSmall, musicSet === item && styles.tabActive)}
                    >
                      <Text>{Strings.getLang(item)}</Text>
                    </View>
                  );
                })}
              </View>

              <View className={styles.voiceContent}>
                {VoiceList?.[musicSet].map(item => {
                  const active = musicSet === item.type && item.code === ringtone;
                  return (
                    <View
                      key={item.code}
                      onClick={() => {
                        publishDps({
                          ringtone: item.code,
                        });
                      }}
                      className={styles.voiceItemBox}
                    >
                      <Image
                        src={active ? item.picActive : item.pic}
                        className={styles.voiceItem}
                      />
                      <Text className={styles.voiceItemName}>{item?.name}</Text>
                    </View>
                  );
                })}
              </View>
            </View>
          </View>
        </View>
      </ScrollView>

      <ConfigProvider
        themeVars={{
          bottomSheetMinHeight: '400',
        }}
      >
        <CountdownActionSheet
          show={showCountDown}
          value={+countDown}
          isSetModeOnly
          // mode="set"
          title={Strings.getLang('countDown')}
          cancelText={Strings.getLang('cancel')}
          okText={Strings.getLang('confirm')}
          hourText={Strings.getLang('hour')}
          minuteText={Strings.getLang('minute')}
          onClickOverlay={() => setShowCountDown(false)}
          onCancel={() => setShowCountDown(false)}
          onStop={() => {
            setCountDown(0);
            setShowCountDown(false);
          }}
          onOk={parmas => {
            setCountDown(parmas.value);
            setShowCountDown(false);
          }}
        />
        <ActionSheet
          show={showUnit}
          title={Strings.getLang('timeUnit')}
          onClose={() => setShowUnit(false)}
          onCancel={() => {
            setShowUnit(false);
          }}
          actions={actions}
          cancelText={Strings.getLang('cancel')}
          onSelect={setTimeMode}
        >
          {/* <View className={styles.footer}>
            <Picker
              columns={['12h', '24h']}
              // valueKey={timeMode}
              defaultIndex={timeMode === '12h' ? 0 : 1}
              onChange={e => {
                unit.current = e.detail.value;
              }}
            />
          </View> */}
        </ActionSheet>
      </ConfigProvider>
    </View>
  );
}

export default Home;
